package ltd.hxya.novel.common.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.fastjson.parser.Feature;
import ltd.hxya.novel.common.constant.redis.RedisConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.lang.reflect.Type;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Component
public class RedisUtils {

    @Autowired
    private StringRedisTemplate redisTemplate;
    private List<String> allKey;

    //对值加一
    public void incr(String key){
        //TODO 单个用户多次计数的问题
        redisTemplate.opsForValue().increment(key);
    }

    public void save(String key,Object value){

        redisTemplate.opsForValue().set(key,JsonUtils.objectToString(value));
    }

    public void delete(String key){
        redisTemplate.delete(key);
    }


    public <T> T get(String key, TypeReference<T> typeReference) {
        String json = redisTemplate.opsForValue().get(key);
        return JSON.parseObject(json,typeReference, Feature.SupportAutoType);

    }
    public List<String> getByPattern(String pattern){
        Set<String> allKey = getAllKey();
        List<String> collect = allKey.stream().filter(key -> {
            if (key.contains(pattern)) {
                return true;
            }
            return false;
        }).collect(Collectors.toList());
        return collect;
    }

    public String get(String key){
        return redisTemplate.opsForValue().get(key);
    }

    public Set<String> getAllKey() {
        Set<String> keys = redisTemplate.keys("*");
        return keys;
    }

    public void clearCache(){
        Set<String> keys = redisTemplate.keys("*");
        redisTemplate.delete(keys);
    }

    public void deleteBatch(Collection<String> collection){
        redisTemplate.delete(collection);
    }

    public List<String> multi(List<String> collection) {
        List<String> strings = redisTemplate.opsForValue().multiGet(collection);
        return strings;
    }
}
